package com.dk.logc.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @Author 林道敬
 * @Date 2024-01-05
 * @Description
 **/
@Component
public class SpringProxy implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringProxy.applicationContext = applicationContext;
        System.err.println("###########spring 加载监听################" + applicationContext);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        if (applicationContext == null)
            return null;
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> requiredType) {
        if (applicationContext == null)
            return null;
        return applicationContext.getBean(requiredType);
    }

    public static <T> Collection<T> getBeansOfType(Class<T> type) {
        return applicationContext.getBeansOfType(type).values();
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
